package cn.schoolwow.quickdao.module.entity.flow.common;

import cn.schoolwow.quickdao.annotation.Ignore;
import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

public class ShouldIgnoreClassFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        boolean shouldIgnoreClass = shouldIgnoreClass(flowContext);
        flowContext.putData("shouldIgnoreClass", shouldIgnoreClass);
    }

    @Override
    public String name() {
        return "是否应该忽略该实体类";
    }

    private boolean shouldIgnoreClass(FlowContext flowContext){
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        Class clazz = (Class) flowContext.checkData("clazz");

        if (clazz.isEnum()) {
            return true;
        }
        if (clazz.getAnnotation(Ignore.class) != null) {
            return true;
        }
        //排除内部类
        if(clazz.isMemberClass()){
            return true;
        }

        //根据类过滤
        if (null != quickDAOConfig.entityOption.ignoreClassList) {
            for (Class _clazz : quickDAOConfig.entityOption.ignoreClassList) {
                if (_clazz.getName().equals(clazz.getName())) {
                    return true;
                }
            }
        }
        //根据包名过滤
        if (null != quickDAOConfig.entityOption.ignorePackageNameList) {
            for (String ignorePackageName : quickDAOConfig.entityOption.ignorePackageNameList) {
                if (clazz.getName().contains(ignorePackageName)) {
                    return true;
                }
            }
        }
        //如果用户已经指定了该实体类,则跳过
        for (Class _clazz : quickDAOConfig.entityOption.entityClassMap.keySet()) {
            if (_clazz.getName().equals(clazz.getName())) {
                return true;
            }
        }
        //执行用户判断逻辑
        if (null != quickDAOConfig.entityOption.ignorePredicate) {
            if (quickDAOConfig.entityOption.ignorePredicate.test(clazz)) {
                return true;
            }
        }
        return false;
    }
}
